from django.utils.encoding import escape_uri_path
from django.http import StreamingHttpResponse
from common.response import JsonResponse
from common.constant import CODE_BUSSINESS_ERROR
import zipfile
import os


def send_file(path, fileName):
    try:
        response = StreamingHttpResponse(read_file(path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(
            escape_uri_path(fileName))
        return response
    except Exception:
        return JsonResponse(data=None, code=CODE_BUSSINESS_ERROR, message="无文件")


def read_file(path, chunk_size=512):
    try:
        with open(path, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    except Exception as e:
        return e


def save_file(f, path):
    with open(path, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)


def zip_dir(dirpath, zipPath):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param zipPath: 压缩文件保存路径+xxxx.zip
    """
    with zipfile.ZipFile(zipPath, 'w', zipfile.ZIP_DEFLATED) as target:
        for file in os.listdir(dirpath):
            file_path = os.path.join(dirpath, file)
            target.write(file_path, file)


def delele_sign(name):
    return delet_path('static'+os.sep+'sign'+os.sep+name)


def delet_path(path):
    try:
        if os.path.exists(path):
            for file in os.listdir(path):
                os.remove(os.path.join(path, file))
            os.rmdir(path)
            return True
        else:
            return False
    except:
        return False
